<?php
include ("./includes/connection.php");
$auxLatO = (double)$_POST['nomLatO'];
$auxLonO = (double)$_POST['nomLonO'];

$auxLatD = (double)$_POST['nomLatD'];
$auxLonD = (double)$_POST['nomLonD'];
$sql = "select recorregut.*, ruta.adresaOrigen, ruta.adresaFinal,Xi,Yi,Xf,Yf, usuari.alias, usuari.foto from(recorregut join usuari on recorregut.idUsuari=usuari.idUsuari)	join ruta on recorregut.idRuta=ruta.idRuta";
//$sql = "Select Xi,Yi,Xf,Yf from recorregut join ruta on recorregut.idRuta=ruta.idRuta";
$result = mysql_query($sql, $conexion);
while ($row = mysql_fetch_array($result)) {

	$latO[] = $row['Xi'];
	$lonO[] = $row['Yi'];
	$latD[] = $row['Xf'];
	$lonD[] = $row['Yf'];
	$usuari[] = $row['alias'];
	$usuariFoto[] = $row['foto'];
	$adresaO[] = $row['adresaOrigen'];
	$adresaD[] = $row['adresaFinal'];
	$tipusU[] = $row['idTipusUsuari'];
	$idRuta[]=$row['idRuta'];
	$preu[]=$row['preu'];
	$places[]=$row['nPlaces'];
	$data[]=$row['data'];

}

for ($i = 0; $i < count($latO); $i++) {

	$resultO = distance((double)$latO[$i], (double)$lonO[$i], $auxLatO, $auxLonO);
	$resultD = distance((double)$latD[$i], (double)$lonD[$i], $auxLatD, $auxLonD);

	if (($resultO < 5) || ($resultD < 5) || ($resultO < 5 && $resultD < 5)) {
		$row1[] = array('latO' => $latO[$i], 'lonO' => $lonO[$i], 'latD' => $latD[$i], 'lonD' => $lonD[$i], 'adresaO' => $adresaO[$i], 'adresaD' => $adresaD[$i], 
		'usuari' => $usuari[$i], 'userFoto' => $usuariFoto[$i], 'tipusUser' => $tipusU[$i],'idRuta'=>$idRuta[$i],'preu'=>$preu[$i],'places'=>$places[$i],'data'=>$data[$i]);
	}

}

echo json_encode($row1);

function distance($lat1, $lon1, $lat2, $lon2) {
	$theta = $lon1 - $lon2;
	$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
	$dist1 = acos($dist);
	$dist2 = rad2deg($dist1);
	$miles = (double)($dist2 * 60 * 1.1515 * 1.609344);

	return $miles;

}
?>